package com.sqy.read;

import com.sqy.common.Num;
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class ReadExcel {

    public static void read(String path, String encoding) throws Exception {
        List<List<String>> result = new ArrayList<>();
        if (path.endsWith(".xlsx") || path.endsWith(".xls")) {
            result = handleData(path);
        }
        FileWriter fw = new FileWriter(Num.PATH);

        for (int i = 0; i < result.size(); i++) {
            String s = null;
            for (int j = 0; j < result.get(i).size(); j++) {
                s = s + result.get(i).get(j);
                fw.write(result.get(i).get(j));

            }


        }
        fw.close();
        //调用读取txt
        ReadTxt.read(Num.PATH, encoding);
    }

    //读取后缀是xlsx的excel表格
    public static List<List<String>> handleData(String excelFilePath) {
        List<List<String>> result = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(excelFilePath);
             Workbook xssfWorkbook = WorkbookFactory.create(inputStream)) {
            //循环每一页，并处理当前的循环页
            for (Sheet sheet : xssfWorkbook) {
                if (sheet == null) {
                    continue;
                }

                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    //Row表示每一行的数据
                    Row row = sheet.getRow(rowNum);
                    if (null != row) {
                        int minColIx = row.getFirstCellNum();
                        int maxColIx = row.getLastCellNum();
                        List<String> rowList = new ArrayList<>();
                        //遍历该行，并获取每一个cell的数据
                        for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                            Cell cell = row.getCell(colIx);
                            if (cell == null) {
                                continue;
                            }
                            rowList.add(cell.toString());
                        }
                        result.add(rowList);
                    }
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
        return result;
    }


}

